<?php
namespace AiSPRDocManager\Controller;

use AiSPRDocManager\Model\Cv as AiCvMModelCv;
use AiSPRDocManager\Model\Utility as AiCvMModelUtility;
use AiSPRDocManager\Model\Db as AiCvMModelDb;

/**
 * Description of Ajax
 *
 * @author Asfer <rmasfer@gmail.com>
 */
class Ajax {

	const ROW_STATUS_INACTIVE = 0;

	public function cvUpload () {
		$aResponse = array();
		$aResponse['status'] = false;
		$aResponse['errors'] = array();
		$aResponse['message'] = '';
		if ($_POST) {

			$oCv = new AiCvMModelCv();
			if ($oCv->isValid($_POST)) {
				$aFile = $_FILES['fileCv'];
				$aMoveFile = wp_upload_bits($aFile['name'], null, file_get_contents($aFile['tmp_name']));

				if ($aMoveFile) {
					$aInsertData = array();

					$aInsertData['name'] = $_POST['textName'];
					$aInsertData['email'] = $_POST['textEmail'];
					$aInsertData['comments'] = $_POST['textareaComments'];
					$aInsertData['file'] = serialize($aMoveFile);
					$aInsertData['status'] = self::ROW_STATUS_INACTIVE;

					$sCurrentDate = date('Y-m-d');
					$aInsertData['date'] = $sCurrentDate;

					$oDbCvManaget = new AiCvMModelDb\CvManager();
					$mInsertResult = $oDbCvManaget->insert(AiCvMModelUtility::getTableName('cv_manager'), $aInsertData);

					if (is_int($mInsertResult)) {
						$aResponse['status'] = true;
					} else {
						$aResponse['status'] = false; //error message
					}
					// var_dump($aInsertData);
					// die('ok');
				} else {
					$aResponse['message'] = 'Something wrong with uploading file. Please try again later';
				}

			} else {
				$aResponse['errors'] = $oCv->getErrors();
			}

		}

		echo json_encode($aResponse);
		die();
	}
}

?>